package com.zhiqian.serializer;

import com.zhiqian.bean.RpcRequest;
import com.zhiqian.bean.RpcResponse;
import com.zhiqian.enums.PackageType;
import com.zhiqian.enums.RpcError;
import com.zhiqian.exception.RpcException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
public class CommonDecoder extends ReplayingDecoder {

    private static final int MAGIC_NUMBER=0xCAFEBABE;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic = in.readInt();
        if (magic!=MAGIC_NUMBER){
            log.error("不识别的协议包：{}",magic);
            throw new RpcException(RpcError.UNKNOWN_PROTOCOL.getMessage());
        }
        int packageCode = in.readInt();
        Class<?> packageClass;
        if (packageCode== PackageType.REQUEST_PACK.getCode()){
            packageClass= RpcRequest.class;
        }else if(packageCode==PackageType.RESPONSE_PACK.getCode()){
            packageClass= RpcResponse.class;
        }else{
            log.error("不识别的数据包:{}",packageCode);
            throw new RpcException(RpcError.UNKNOWN_PACKAGE_TYPE.getMessage());
        }
        int serializerCode = in.readInt();
        CommonSerializer serializer=CommonSerializer.getByCode(serializerCode);
        if (serializer==null){
            log.error("不识别的序列化方式：{}",serializerCode);
            throw new RpcException(RpcError.UNKNOWN_SERIALIZER.getMessage());
        }
        int len = in.readInt();
        byte[] bytes=new byte[len];
        in.readBytes(bytes);
        Object obj=serializer.deserialize(bytes,packageClass);
        out.add(obj);
    }
}
